package com.zj.leetcode.medium.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @program: algorithm
 * @description: 在每个树行中找最大值
 * 515 find-largest-value-in-each-tree-row
 * @author: Zhang Bo
 * @create: 2022-06-14 16:46:00
 **/
public class FindLargestValueInEachTreeRow {
    public static void main(String[] args) {
        Solution solution = new FindLargestValueInEachTreeRow().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public List<Integer> largestValues(TreeNode root) {

            if(root == null){
                return new ArrayList<>();
            }
            List<Integer> list = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);

            while (queue.size() > 0){
                //查找最大值
                int max = Integer.MIN_VALUE;
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode temp = queue.poll();
                    if(temp != null){
                        max = Math.max(temp.val, max);
                    }
                    queue.add(temp);
                }
                list.add(max);

                //更新下一层node
                for (int i = 0; i < size; i++) {
                    TreeNode poll = queue.poll();
                    if(poll.left != null){
                        queue.add(poll.left);
                    }
                    if(poll.right != null){
                        queue.add(poll.right);
                    }
                }
            }
            return list;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
